package com.sskj.mine.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.App;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.presenter.RegisterFragmentPresenter;
import com.sskj.mine.ui.activity.LoginActivity;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/*
 *注册Fragment
 */
public class RegisterFragment extends BaseFragment<RegisterFragmentPresenter> {

    @BindView(R2.id.etPhone)
    EditText etPhone;
    @BindView(R2.id.etCode)
    EditText etCode;
    @BindView(R2.id.tvCode)
    TextView tvCode;
    @BindView(R2.id.etPwd)
    EditText etPwd;
    @BindView(R2.id.ivTogglePwd)
    ImageView ivTogglePwd;
    @BindView(R2.id.etPwdAgain)
    EditText etPwdAgain;
    @BindView(R2.id.ivTogglePwdAgain)
    ImageView ivTogglePwdAgain;
    @BindView(R2.id.etInviteCode)
    EditText etInviteCode;
    @BindView(R2.id.checkBox)
    CheckBox checkBox;
    @BindView(R2.id.tvAgreement)
    TextView tvAgreement;
    @BindView(R2.id.btRegister)
    TextView btRegister;
    DisposableSubscriber disposableSubscriber;
    @BindView(R2.id.rl_num)
    RelativeLayout rlNum;
    @BindView(R2.id.rl_code)
    LinearLayout rlCode;
    @BindView(R2.id.rl_pwd)
    RelativeLayout rlPwd;
    @BindView(R2.id.rl_pwd_reset)
    RelativeLayout rlPwdReset;
    @BindView(R2.id.rl_invite_code)
    FrameLayout rlInviteCode;
    @BindView(R2.id.rl_check)
    LinearLayout rlCheck;
    private boolean isSeeAgain;
    private boolean isSee;
    private boolean isRegister = false;  // true 注册  false 下一步
    private String phoneNumber;
    private String code;
    private String registerPwdCon;
    private String registerPwdTwoCon;
    private String registerInvitationCodeCon;

    @Override
    protected int getLayoutId() {
        return R.layout.mine_fragment_register;
    }

    @Override
    protected RegisterFragmentPresenter getPresenter() {
        return new RegisterFragmentPresenter();
    }

    @Override
    public void initView() {
        ClickUtil.click(tvCode, () -> {   // 获取短信验证码
            if (CheckUtil.isEmail(etPhone.getText().toString())) {
                tvCode.setEnabled(false);
                mPresenter.sendEmailCode(etPhone.getText().toString());
            } else if (CheckUtil.isMobile(etPhone.getText().toString())) {
                tvCode.setEnabled(false);
                mPresenter.sendCode(etPhone.getText().toString());
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity0));
                etPhone.setText("");
            }
        });
        ClickUtil.click(200, ivTogglePwdAgain, () -> {
            if (isSeeAgain) {
                isSeeAgain = false;
                etPwdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                ivTogglePwdAgain.setImageResource(R.mipmap.mine_icon_unsee);
            } else {
                isSeeAgain = true;
                etPwdAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                ivTogglePwdAgain.setImageResource(R.mipmap.mine_icon_see);
            }
        });
        ClickUtil.click(200, ivTogglePwd, () -> {
            if (isSee) {
                isSee = false;
                etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                ivTogglePwd.setImageResource(R.mipmap.mine_icon_unsee);
            } else {
                isSee = true;
                etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                ivTogglePwd.setImageResource(R.mipmap.mine_icon_see);
            }
        });

        ClickUtil.click(btRegister, () -> {
            if (!isRegister) {  // 下一步
                phoneNumber = etPhone.getText().toString().trim();
                code = etCode.getText().toString().trim();
                if (!CheckUtil.isMobile(phoneNumber) && !CheckUtil.isEmail(phoneNumber)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity0));
                    etPhone.setText("");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity4));
                    return;
                }
                mPresenter.checkCode(phoneNumber, code);
            } else {
                registerPwdCon = etPwd.getText().toString().trim();
                registerPwdTwoCon = etPwdAgain.getText().toString().trim();
                registerInvitationCodeCon = etInviteCode.getText().toString().trim();


                if (!CheckUtil.isPayPwd(registerPwdCon) || !CheckUtil.isPayPwd(registerPwdTwoCon)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity5));
                    return;
                }
                if (!registerPwdCon.equals(registerPwdTwoCon)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity6));
                    return;
                }
                if (TextUtils.isEmpty(registerInvitationCodeCon)) {
                    ToastUtil.showShort("请输入邀请码");
                    return;
                }
                if (!checkBox.isChecked()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRegisterActivity7));
                    return;
                }

                mPresenter.register(phoneNumber, registerPwdCon, registerPwdTwoCon, code, TextUtils.isEmpty(registerInvitationCodeCon) ? null : registerInvitationCodeCon);
            }

        });

        ClickUtil.click(tvAgreement, () -> ARouter.getInstance().build(RConfig.MINE_WEB).navigation());
    }

    public void sendCodeOk() {
        startCount();
    }

    public void sendCodeError() {
        tvCode.setEnabled(true);
    }

    /**
     * 获取验证码倒计时
     */
    public void startCount() {
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                tvCode.setText(String.format(App.INSTANCE.getString(R.string.mineRegisterActivity8), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                tvCode.setText(App.INSTANCE.getString(R.string.mineRegisterActivity9));
                tvCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 6) {
                    btRegister.setEnabled(true);
                } else {
                    btRegister.setEnabled(false);
                }
            }
        });

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void registerSuccess() {
        ((LoginActivity) getActivity()).skipFragment();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DisposUtil.close(disposableSubscriber);
    }

    public static RegisterFragment newInstance() {

        Bundle args = new Bundle();

        RegisterFragment fragment = new RegisterFragment();
        fragment.setArguments(args);
        return fragment;
    }

    // 验证码校验成功
    public void nextStep() {
        rlNum.setVisibility(View.GONE);
        rlCode.setVisibility(View.GONE);
        rlPwd.setVisibility(View.VISIBLE);
        rlPwdReset.setVisibility(View.VISIBLE);
        rlInviteCode.setVisibility(View.VISIBLE);
        rlCheck.setVisibility(View.VISIBLE);
        btRegister.setText("注册");
        Log.i("info", phoneNumber + "    " + code);
        isRegister = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            rlNum.setVisibility(View.VISIBLE);
            rlCode.setVisibility(View.VISIBLE);
            rlPwd.setVisibility(View.GONE);
            rlPwdReset.setVisibility(View.GONE);
            rlInviteCode.setVisibility(View.GONE);
            rlCheck.setVisibility(View.GONE);
            btRegister.setText("下一步");
            isRegister = false;
        }
    }
}
